package com.aifeng.hassan_food.sale

import android.annotation.SuppressLint
import android.os.Bundle
import com.aifeng.base.BaseActivity
import com.aifeng.base.setCompoundDrawable
import com.aifeng.common_ui.base.oneClick
import com.aifeng.common_ui.helper.*
import com.aifeng.hassan_food.R
import com.aifeng.hassan_food.mine.RealActivity
import com.aifeng.utils.DialogHelper.showHintDialog
import com.aifeng.utils.DialogHelper.showPayDialog
import com.aifeng.utils.applyFlowableSchedulers
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.getExtra
import com.aifeng.utils.subscribeByNoError
import com.aifeng.viewmodel.OrderViewModel
import com.cuieney.rxpay_annotation.WX
import com.cuieney.sdk.rxpay.RxPay
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzy.okgo.utils.OkLogger
import io.reactivex.rxkotlin.subscribeBy
import kotlinx.android.synthetic.main.activity_confirm_pay.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.json.JSONObject
import org.koin.androidx.viewmodel.ext.android.getViewModel

@WX(packageName = "com.aifeng.hassan_food")
class ConfirmPayActivity : BaseActivity() {

    private var mBalance = 0.0
    private var mPayTotal = 0.0
    private var isReal = false

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_confirm_pay)
        initTitle(title = "确认支付", divider = false)

        val totalSecond = 15 * 60L
        getViewModel().countDown(totalSecond)
            .bindLifeCycle(getLifecycleOwner())
            .subscribe {
                pay_duration.text = "支付剩余时间 ${TimeHelper.formatTimeClock(totalSecond - it)}"
            }

        getData()
    }

    override fun getViewModel() = getViewModel<OrderViewModel>()

    override fun onStart() {
        super.onStart()
        isReal = getString("realName").isNotEmpty()
    }

    @SuppressLint("SetTextI18n")
    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        val total = intent.getExtra("price").toNotDouble()
        val fee = intent.getExtra("express").toNotDouble()
        mPayTotal = total + fee
        bt_pay.text = "确认支付 ¥ ${mPayTotal.formatDecimal()}"

        pay_check1.setCompoundDrawable(
            leftDrawable = R.mipmap.icon_pay01,
            leftSize = 30f,
            rightDrawable = R.drawable.ic_adress_selector
        )
        pay_check2.setCompoundDrawable(
            leftDrawable = R.mipmap.icon_pay02,
            leftSize = 30f,
            rightDrawable = R.drawable.ic_adress_selector
        )
        pay_check3.setCompoundDrawable(
            leftDrawable = R.mipmap.icon_pay03,
            leftSize = 30f,
            rightDrawable = R.drawable.ic_adress_selector
        )

        bt_pay.oneClick {
            if (!pay_check1.isChecked
                && !pay_check2.isChecked
                && !pay_check3.isChecked
            ) {
                toast("请选择支付方式！")
                return@oneClick
            }

            if (pay_check1.isChecked) {
                if (!isReal) {
                    showHintDialog(
                        title = "实名认证",
                        hint = "您还未进行实名认证，是否现在去认证？",
                        sure = "去认证"
                    ) { startActivity<RealActivity>() }
                    return@oneClick
                }

                if (mBalance < mPayTotal) {
                    toast("当前可用余额不足，请使用其他支付方式")
                    return@oneClick
                }

                showPayDialog() {
                    getViewModel().payOption(
                        intent.getExtra("orderNo"),
                        "balance",
                        it
                    )
                        .bindLifeCycle(getLifecycleOwner())
                        .subscribeByNoError(
                            event = getViewModel(),
                            onSuccess ={
                                val orderIndex = intent.getExtra("orderIndex")
                                if (orderIndex.isNotEmpty()) {
                                    LiveEventBus.get("orderList").post("pay,$orderIndex")
                                    LiveEventBus.get("orderDetail").post("refresh")

                                    startActivity<ConfirmDoneActivity>(
                                        "orderId" to intent.getExtra("orderId"),
                                        "orderIndex" to intent.getExtra("orderIndex")
                                    )
                                } else {
                                    startActivity<ConfirmDoneActivity>(
                                        "orderId" to intent.getExtra("orderId")
                                    )
                                }

                                ActivityStack.screenManager.popActivities(this::class.java)
                            }
                        )
                }
            }
            else {
                getViewModel().payOption(
                    intent.getExtra("orderNo"),
                    if (pay_check2.isChecked) "wx" else "ali"
                )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByNoError(
                        event = getViewModel(),
                        onSuccess = { data ->
                            with(RxPay(baseContext)) {
                                if (pay_check2.isChecked) {
                                    val json = JSONObject(data)
                                    val newJson = JSONObject()
                                    newJson.put("packageValue", json.optNotNull("package"))
                                    newJson.put("sign", json.optNotNull("sign"))
                                    newJson.put("partnerId", json.optNotNull("partnerid"))
                                    newJson.put("prepayId", json.optNotNull("prepayid"))
                                    newJson.put("nonceStr", json.optNotNull("noncestr"))
                                    newJson.put("timeStamp", json.optNotNull("timestamp"))
                                    requestWXpay(newJson.toString())
                                } else {
                                    requestAlipay(data)
                                }
                            }
                                .compose(applyFlowableSchedulers())
                                .subscribeBy(
                                    onNext = {
                                        if (it) {
                                            val orderIndex = intent.getExtra("orderIndex")
                                            if (orderIndex.isNotEmpty()) {
                                                LiveEventBus.get("orderList").post("pay,$orderIndex")
                                                LiveEventBus.get("orderDetail").post("refresh")

                                                startActivity<ConfirmDoneActivity>(
                                                    "orderId" to intent.getExtra("orderId"),
                                                    "orderIndex" to intent.getExtra("orderIndex")
                                                )
                                            } else {
                                                startActivity<ConfirmDoneActivity>(
                                                    "orderId" to intent.getExtra("orderId")
                                                )
                                            }

                                            ActivityStack.screenManager.popActivities(this::class.java)
                                        } else {
                                            toast("支付失败，请重试！")
                                        }
                                    },
                                    onError = { OkLogger.printStackTrace(it) }
                                )
                        }
                    )
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().userInfo(getString("userId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByNoError(
                event = getViewModel(),
                onSuccess = {
                    val user = JSONObject(it).optJSONObject("user") ?: JSONObject()
                    mBalance = user.optNotNull("balance").toNotDouble()
                    isReal = user.optNotNull("realname").isNotEmpty()
                    pay_balance.text = "可用余额${mBalance.formatDecimal()}元"
                }
            )
    }

}
